import all from "@/assets/svg/all.svg";
import photo from "@/assets/svg/photo.svg";
import video from "@/assets/svg/video.svg";
import { SvgIcon } from "@/components/ui/SvgIcon";
import { MaterialIcons } from "@expo/vector-icons";
import * as ImagePicker from "expo-image-picker";
import * as MediaLibrary from "expo-media-library";

import {
  forwardRef,
  useEffect,
  useImperativeHandle,
  useState,
} from "react";
import {
  ActivityIndicator,
  Dimensions,
  FlatList,
  Image,
  StyleSheet,
  Text,
  TouchableOpacity,
  View,
} from "react-native";
import { debugMediaPermissions } from "../debug-media-permissions";

const { width } = Dimensions.get("window");
const ITEM_SIZE = width / 5 - 2;

const TABS = [
  { type: "all", label: "全部" },
  { type: "photo", label: "图片" },
  { type: "video", label: "视频" },
] as const;

export interface MediaItem {
  id: string;
  uri: string;
  type: "photo" | "video" | "camera";
  duration?: number;
  creationTime: number;
  width?: number;
  height?: number;
}

interface MediaGridProps {
  selectedItems: string[];
  filterType: "all" | "photo" | "video";
  onItemPress: (item: MediaItem) => void;
  onCameraPress: () => void;
  onFilterChange: (filterType: "all" | "photo" | "video") => void;
  onSingleSelect?: (item: MediaItem) => void;
  onMultipleSelect?: (items: MediaItem[]) => void;
  mode?: "single" | "multiple";
}

/**
 * 媒体网格组件
 * 封装媒体列表的渲染逻辑，包括相机按钮和媒体项
 */
const MediaGrid = forwardRef(
  (
    {
      selectedItems,
      filterType,
      onItemPress,
      onCameraPress,
      onFilterChange,
      onSingleSelect,
      onMultipleSelect,
      mode = "single",
    }: MediaGridProps,
    ref
  ) => {
    const [media, setMedia] = useState<MediaItem[]>([]);
    const [loading, setLoading] = useState(true);
    const [permissionError, setPermissionError] = useState<string | null>(null);

    /**
     * 根据ID获取媒体项
     */
    const getMediaByIds = (ids: string[]): MediaItem[] => {
      return media.filter(
        (item) => ids.includes(item.id) && item.type !== "camera"
      );
    };

    useImperativeHandle(ref, () => ({
      getMediaByIds,
    }));

    useEffect(() => {
      loadMedia();
      // eslint-disable-next-line react-hooks/exhaustive-deps
    }, [filterType]);

    /**
     * 打开系统相册
     */
    const openSystemAlbum = async () => {
      try {
        console.log("打开系统相册: 检查权限...");
        const { status } = await ImagePicker.requestMediaLibraryPermissionsAsync();
        if (status !== "granted") {
          setPermissionError("需要相册权限才能访问照片和视频，请在设置中开启权限");
          return;
        }

        // 兼容不同 expo-image-picker 版本的 mediaTypes
        const anyPicker = ImagePicker as unknown as Record<string, any>;
        const mediaTypesParam = anyPicker?.MediaType
          ? [anyPicker.MediaType.image, anyPicker.MediaType.video]
          : anyPicker?.MediaTypeOptions?.All ?? anyPicker?.MediaTypeOptions?.Images;

        console.log("打开系统相册: 启动选择器...", { mediaTypesParam });
        const result = await ImagePicker.launchImageLibraryAsync({
          mediaTypes: mediaTypesParam as any,
          allowsEditing: false,
          quality: 1,
          allowsMultipleSelection: (mode as string) === "multiple",
        } as any);

        if (result.canceled) {
          console.log("用户取消选择");
          return;
        }

        const assets = result.assets ?? [];
        console.log("系统相册返回文件数:", assets.length);

        const converted: MediaItem[] = assets.map((a: any) => ({
          id: a.assetId || a.id || a.uri,
          uri: a.uri,
          type: (a.type === "image" ? "photo" : "video") as "photo" | "video",
          duration: a.duration,
          creationTime: Date.now(),
          width: a.width,
          height: a.height,
        }));

        if (mode === "single" && onSingleSelect && converted[0]) {
          onSingleSelect(converted[0]);
        } else if (mode === "multiple" && onMultipleSelect) {
          onMultipleSelect(converted);
        }
      } catch (error) {
        console.error("打开系统相册失败:", error);
      }
    };

    /**
     * 加载媒体文件
     */
    const loadMedia = async () => {
      try {
        console.log('=== MediaGrid: 开始加载媒体文件 ===');
        setLoading(true);

        // 首先检查权限
        console.log('MediaGrid: 检查权限...');
        const currentPerm = await MediaLibrary.getPermissionsAsync();
        console.log('MediaGrid: 当前权限状态:', currentPerm.status, currentPerm.accessPrivileges);
        
        if (currentPerm.status !== "granted" || currentPerm.accessPrivileges !== 'all') {
          console.log("MediaGrid: 媒体库权限未授予/非全部，请求权限...");
          const requestResult = await MediaLibrary.requestPermissionsAsync({ accessPrivileges: 'all' as any });
          console.log('MediaGrid: 权限请求结果:', requestResult);
          
          if (requestResult.status !== "granted") {
            console.log("MediaGrid: 权限被拒绝");
            setPermissionError("需要相册权限才能访问照片和视频，请在设置中开启权限");
            setMedia([]);
            return;
          }
        }
        
        // 清除权限错误
        setPermissionError(null);
        console.log('MediaGrid: 权限已获取，开始加载媒体文件...');

        let mediaType:
          | MediaLibrary.MediaTypeValue
          | MediaLibrary.MediaTypeValue[] = [
          MediaLibrary.MediaType.photo,
          MediaLibrary.MediaType.video,
        ];
        if (filterType === "photo") {
          mediaType = MediaLibrary.MediaType.photo;
        } else if (filterType === "video") {
          mediaType = MediaLibrary.MediaType.video;
        }

        console.log('MediaGrid: 获取媒体文件，类型:', filterType);
        // 首次获取（带类型与安全的排序）
        let assets = await MediaLibrary.getAssetsAsync({
          first: 500,
          mediaType: mediaType,
          sortBy: [MediaLibrary.SortBy.creationTime],
        });

        // 兜底：如果没有获取到，则尝试不带排序与不限定类型
        if (!assets || assets.totalCount === 0) {
          console.log('MediaGrid: 首次为0，尝试兜底获取...');
          try {
            assets = await MediaLibrary.getAssetsAsync({ first: 500 });
          } catch (e) {
            console.log('MediaGrid: 兜底获取失败:', (e as Error).message);
          }
        }

        console.log('MediaGrid: 获取到的资产信息:', {
          totalCount: assets?.totalCount ?? 0,
          assetsCount: assets?.assets?.length || 0,
          hasEndCursor: !!assets?.endCursor,
        });

        let formattedMedia: MediaItem[] = [];

        if (assets?.assets && assets.assets.length > 0) {
          formattedMedia = assets.assets.map((asset) => ({
            id: asset.id,
            uri: asset.uri,
            type:
              asset.mediaType === MediaLibrary.MediaType.photo
                ? "photo"
                : "video",
            duration: asset.duration,
            creationTime: asset.creationTime,
            width: asset.width,
            height: asset.height,
          }));
          
          console.log('MediaGrid: 格式化后的媒体文件数量:', formattedMedia.length);
          if (formattedMedia.length > 0) {
            console.log('MediaGrid: 第一个文件信息:', {
              id: formattedMedia[0].id,
              uri: formattedMedia[0].uri,
              type: formattedMedia[0].type,
              width: formattedMedia[0].width,
              height: formattedMedia[0].height,
            });
          }
        } else {
          console.log('MediaGrid: 没有找到媒体文件');
        }

        // 只在"全部"标签下显示相机按钮；若完全没有媒体，优先提示打开系统相册
        if (filterType === "all") {
          const list = formattedMedia.length > 0
            ? [{ id: "camera", uri: "", type: "camera", creationTime: Date.now() }, ...formattedMedia]
            : [{ id: "camera", uri: "", type: "camera", creationTime: Date.now() }];
          setMedia(list);
        } else {
          setMedia(formattedMedia);
        }
        
        console.log('MediaGrid: 最终设置的媒体文件数量:', formattedMedia.length);
      } catch (error) {
        console.error("MediaGrid: 加载媒体文件失败:", error);
        setPermissionError("加载媒体文件失败，请检查权限设置");
        setMedia([]);
      } finally {
        setLoading(false);
        console.log('MediaGrid: 加载完成');
      }
    };

    /**
     * 格式化视频时长显示
     */
    const formatDuration = (seconds: number): string => {
      const mins = Math.floor(seconds / 60);
      const secs = Math.floor(seconds % 60);
      return `${mins}:${secs.toString().padStart(2, "0")}`;
    };

    /**
     * 渲染单个媒体项
     */
    const renderMediaItem = ({ item }: { item: MediaItem }) => {
      if (item.type === "camera") {
        return (
          <TouchableOpacity
            style={[styles.mediaItem, styles.cameraItem]}
            onPress={onCameraPress}
            activeOpacity={0.8}
          >
            <View style={styles.cameraContent}>
              <MaterialIcons name="camera-alt" size={32} color="#666" />
            </View>
          </TouchableOpacity>
        );
      }

      const isSelected = selectedItems.includes(item.id);

      const handleItemPress = () => {
        if (mode === "single" && onSingleSelect) {
          onSingleSelect(item);
          return;
        }
        onItemPress(item);
      };

      return (
        <TouchableOpacity
          style={[styles.mediaItem, isSelected && styles.selectedItem]}
          onPress={handleItemPress}
          activeOpacity={0.8}
        >
          <Image source={{ uri: item.uri }} style={styles.mediaImage} />

          {item.type === "video" && (
            <View style={styles.videoIndicator}>
              <MaterialIcons name="play-arrow" size={12} color="#fff" />
            </View>
          )}

          {isSelected && (
            <View style={styles.selectedIndicator} />
          )}
        </TouchableOpacity>
      );
    };

    return (
      <View style={{ flex: 1 }}>
        <View style={styles.tabContainer}>
          {TABS.map((tab) => (
            <TouchableOpacity key={tab.type} style={[styles.tab, filterType === tab.type && styles.activeTab]} onPress={() => onFilterChange(tab.type)}>
              <View style={styles.tabContent}>
                {tab.type === 'all' && <SvgIcon Icon={all} size={14} color={filterType === tab.type ? '#fff' : '#666'} style={styles.tabIcon}/>}
                {tab.type === 'photo' && <SvgIcon Icon={photo} size={14} color={filterType === tab.type ? '#fff' : '#666'} style={styles.tabIcon}/>}
                {tab.type === 'video' && <SvgIcon Icon={video} size={14} color={filterType === tab.type ? '#fff' : '#666'} style={styles.tabIcon}/>}
                <Text style={[ styles.tabText, filterType === tab.type && styles.activeTabText]}>
                  {tab.label}
                </Text>
              </View>
            </TouchableOpacity>
          ))}
          <TouchableOpacity style={styles.testButton} onPress={debugMediaPermissions}>
            <Text style={styles.testButtonText}>测试权限</Text>
          </TouchableOpacity>
          <TouchableOpacity style={styles.albumButton} onPress={openSystemAlbum}>
            <Text style={styles.albumButtonText}>打开相册</Text>
          </TouchableOpacity>
        </View>
        
        {loading ? (
          <View style={styles.loadingContainer}>
            <ActivityIndicator size="large" color="#007AFF" />
            <Text style={styles.loadingText}>加载中...</Text>
          </View>
        ) : permissionError ? (
          <View style={styles.errorContainer}>
            <MaterialIcons name="error-outline" size={48} color="#FF3B30" />
            <Text style={styles.errorText}>{permissionError}</Text>
            <TouchableOpacity style={styles.retryButton} onPress={loadMedia}>
              <Text style={styles.retryButtonText}>重试</Text>
            </TouchableOpacity>
            <TouchableOpacity style={styles.debugButton} onPress={debugMediaPermissions}>
              <Text style={styles.debugButtonText}>调试权限</Text>
            </TouchableOpacity>
          </View>
        ) : (
          <FlatList
            data={media}
            renderItem={renderMediaItem}
            keyExtractor={(item) => item.id}
            numColumns={5}
            contentContainerStyle={styles.gridContainer}
            showsVerticalScrollIndicator={false}
          />
        )}
      </View>
    );
  }
);

MediaGrid.displayName = "MediaGrid";

export default MediaGrid;

const styles = StyleSheet.create({
  loadingContainer: {
    flex: 1,
    justifyContent: "center",
    alignItems: "center",
    paddingVertical: 40,
  },
  tabContainer: {
    flexDirection: "row",
    padding: 10,
    paddingTop: 10,
    backgroundColor: "#fff",
  },
  tab: {
    paddingHorizontal: 12,
    paddingVertical: 6,
    borderRadius: 18,
    marginRight: 8,
    backgroundColor: "#f0f0f0",
  },
  tabContent: {
    flexDirection: 'row',
    alignItems: 'center',
  },
  tabIcon: {
    marginRight: 4,
  },
  activeTab: {
    backgroundColor: "#222",
  },
  tabText: {
    fontSize: 12,
    color: "#666",
  },
  activeTabText: {
    color: "#fff",
  },
  gridContainer: {
    paddingHorizontal: 10,
  },
  mediaItem: {
    width: ITEM_SIZE,
    height: ITEM_SIZE,
    margin: 2,
    position: "relative",
  },
  selectedItem: {
    opacity: 0.8,
  },
  mediaImage: {
    width: "100%",
    height: "100%",
  },
  videoIndicator: {
    position: "absolute",
    bottom: 4,
    right: 4,
    backgroundColor: "rgba(0,0,0,0.7)",
    paddingHorizontal: 4,
    paddingVertical: 2,
    borderRadius: 2,
  },
  videoDuration: {
    display: 'none',
  },
  selectedIndicator: {
    position: "absolute",
    top: 6,
    right: 6,
    width: 10,
    height: 10,
    borderRadius: 5,
    backgroundColor: "#007AFF",
  },
  selectedText: {
    display: 'none',
  },
  cameraItem: {
    backgroundColor: "#f5f5f5",
    justifyContent: "center",
    alignItems: "center",
  },
  cameraContent: {
    alignItems: "center",
    justifyContent: "center",
  },
  cameraText: {
    display: 'none',
  },
  loadingText: {
    marginTop: 12,
    fontSize: 14,
    color: "#666",
  },
  errorContainer: {
    flex: 1,
    justifyContent: "center",
    alignItems: "center",
    paddingHorizontal: 20,
  },
  errorText: {
    marginTop: 16,
    fontSize: 14,
    color: "#666",
    textAlign: "center",
    lineHeight: 20,
  },
  retryButton: {
    marginTop: 20,
    paddingHorizontal: 20,
    paddingVertical: 10,
    backgroundColor: "#007AFF",
    borderRadius: 8,
  },
  retryButtonText: {
    color: "#fff",
    fontSize: 14,
    fontWeight: "500",
  },
  debugButton: {
    marginTop: 12,
    paddingHorizontal: 20,
    paddingVertical: 10,
    backgroundColor: "#FF9500",
    borderRadius: 8,
  },
  debugButtonText: {
    color: "#fff",
    fontSize: 14,
    fontWeight: "500",
  },
  testButton: {
    paddingHorizontal: 12,
    paddingVertical: 6,
    borderRadius: 18,
    marginLeft: 8,
    backgroundColor: "#f0f0f0",
  },
  testButtonText: {
    fontSize: 12,
    color: "#666",
  },
  albumButton: {
    paddingHorizontal: 12,
    paddingVertical: 6,
    borderRadius: 18,
    marginLeft: 8,
    backgroundColor: "#f0f0f0",
  },
  albumButtonText: {
    fontSize: 12,
    color: "#666",
  },
});
